<template>
  <div class="app-container">
    <el-dialog :title="pageTitle" :visible.sync="dialogFormVisible" :before-close="beforeClose">
      <el-form :model="form">
        <el-form-item label="菜单名称：" :label-width="formLabelWidth">
          <el-input v-model="form.title" minlength="2" maxlength="10" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单地址：" :label-width="formLabelWidth">
          <el-input v-model="form.url" placeholder="请输入菜单地址" />
        </el-form-item>
        <el-form-item label="图标名称：" :label-width="formLabelWidth">
          <el-input v-model="form.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序比重：" :label-width="formLabelWidth">
          <el-input v-model="form.sort" type="number" min="0" max="99" placeholder="请输入排序比重" />
        </el-form-item>
        <el-form-item label="选择主菜单：" :label-width="formLabelWidth">
          <el-select v-model="form.pid" placeholder="请选择主菜单">
            <el-option
              v-for="item in parentMenus"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canel">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { handle, getFirstMenu } from '@/api/menu'
export default {
  name: 'MenuHandle',
  data() {
    return {
      form: {
        id: 'new',
        pid: '',
        title: '',
        url: '',
        icon: '',
        sort: ''
      },
      formLabelWidth: '120px',
      dialogFormVisible: false,
      parentMenus: [],
      pageTitle: '添加菜单'
    }
  },

  methods: {
    beforeClose() {
      this.canel()
    },

    add() {
      this.getFirstMenu()
      this.form.id = 'new'
      this.pageTitle = '添加菜单'
      this.dialogFormVisible = true
    },

    edit(item) {
      this.getFirstMenu()
      this.form.id = item.id
      this.form.pid = item.pid
      this.form.title = item.title
      this.form.url = item.url
      this.form.icon = item.icon
      this.form.sort = item.sort
      this.pageTitle = '编辑菜单'
      this.dialogFormVisible = true
    },

    canel() {
      this.dialogFormVisible = false
      this.form.id = 'new'
      this.form.pid = ''
      this.form.title = ''
      this.form.url = ''
      this.form.icon = ''
      this.form.sort = ''
    },

    sure() {
      handle(this.form).then(res => {
        Message({
          message: res.data.info,
          type: 'success',
          duration: 2000
        })
        this.$emit('afterSave')
        this.canel()
      })
    },

    getFirstMenu() {
      getFirstMenu({}).then(res => {
        this.parentMenus = res.data
      })
    }
  }
}
</script>
